// Package micro 实现微观阶序量子编码
// 基于四维一体法则的第一维度：微观阶序
package micro

import (
	"fmt"
	"math"
	"math/cmplx"
)

// QuantumState 量子态结构
type QuantumState struct {
	Amplitudes    []complex128 // 量子振幅
	NumQubits     int          // 量子比特数
	Coherence     float64      // 相干性度量 (0-1)
	CoherenceTime float64      // 相干时间（微秒）
	Phase         float64      // 相位
}

// QuantumSequenceEncoder 量子序列编码器
type QuantumSequenceEncoder struct {
	NumQubits          int     // 量子比特数
	CoherenceThreshold float64 // 相干性阈值
	DefaultPhase       float64 // 默认相位
}

// NewQuantumSequenceEncoder 创建新的量子序列编码器
func NewQuantumSequenceEncoder(numQubits int, coherenceThreshold float64) *QuantumSequenceEncoder {
	return &QuantumSequenceEncoder{
		NumQubits:          numQubits,
		CoherenceThreshold: coherenceThreshold,
		DefaultPhase:       0.0,
	}
}

// EncodeMicroSequence 将数据编码为量子叠加态
func (e *QuantumSequenceEncoder) EncodeMicroSequence(data []byte) (*QuantumState, error) {
	if len(data) == 0 {
		return nil, fmt.Errorf("空数据无法编码")
	}

	// 转换数据为二进制字符串
	bitString := e.bytesToBitString(data)
	
	// 创建量子叠加态
	state, err := e.CreateSuperposition(bitString)
	if err != nil {
		return nil, fmt.Errorf("创建叠加态失败: %w", err)
	}

	// 验证相干性
	if state.Coherence < e.CoherenceThreshold {
		return nil, fmt.Errorf("量子相干性不足: %.2f < %.2f", state.Coherence, e.CoherenceThreshold)
	}

	return state, nil
}

// CreateSuperposition 创建量子叠加态
func (e *QuantumSequenceEncoder) CreateSuperposition(bits string) (*QuantumState, error) {
	if len(bits) == 0 {
		return nil, fmt.Errorf("位串不能为空")
	}

	// 限制比特串长度
	if len(bits) > e.NumQubits {
		bits = bits[:e.NumQubits]
	}

	// 计算状态空间大小 (2^n)
	stateSize := int(math.Pow(2, float64(e.NumQubits)))
	amplitudes := make([]complex128, stateSize)

	// 使用哈达玛变换创建均匀叠加态
	for i := 0; i < stateSize; i++ {
		// 初始化为均匀叠加
		amplitude := 1.0 / math.Sqrt(float64(stateSize))
		
		// 根据输入比特调整相位
		phase := e.calculatePhase(i, bits)
		amplitudes[i] = complex(amplitude*math.Cos(phase), amplitude*math.Sin(phase))
	}

	// 归一化
	amplitudes = e.normalize(amplitudes)

	// 计算相干性
	coherence := e.calculateCoherence(amplitudes)

	return &QuantumState{
		Amplitudes:    amplitudes,
		NumQubits:     e.NumQubits,
		Coherence:     coherence,
		CoherenceTime: 100.0, // 默认100微秒
		Phase:         e.DefaultPhase,
	}, nil
}

// ApplyPhaseShift 应用相位偏移
func (e *QuantumSequenceEncoder) ApplyPhaseShift(state *QuantumState, phase float64) error {
	if state == nil {
		return fmt.Errorf("量子态不能为空")
	}

	phaseShift := cmplx.Exp(complex(0, phase))
	for i := range state.Amplitudes {
		state.Amplitudes[i] *= phaseShift
	}

	state.Phase += phase
	return nil
}

// MeasureState 测量量子态
func (e *QuantumSequenceEncoder) MeasureState(state *QuantumState) ([]byte, error) {
	if state == nil {
		return nil, fmt.Errorf("量子态不能为空")
	}

	// 计算每个基态的概率
	probabilities := make([]float64, len(state.Amplitudes))
	for i, amp := range state.Amplitudes {
		probabilities[i] = math.Pow(cmplx.Abs(amp), 2)
	}

	// 选择概率最大的状态
	maxProb := 0.0
	maxIndex := 0
	for i, prob := range probabilities {
		if prob > maxProb {
			maxProb = prob
			maxIndex = i
		}
	}

	// 将索引转换为二进制字符串
	bitString := fmt.Sprintf("%0*b", state.NumQubits, maxIndex)
	
	// 转换为字节
	return e.bitStringToBytes(bitString), nil
}

// IsSuperposition 判断是否处于叠加态
func (s *QuantumState) IsSuperposition() bool {
	// 如果只有一个振幅接近1，其他接近0，则不是叠加态
	count := 0
	for _, amp := range s.Amplitudes {
		prob := math.Pow(cmplx.Abs(amp), 2)
		if prob > 0.9 {
			count++
		}
	}
	return count != 1
}

// GetProbabilities 获取各基态的概率分布
func (s *QuantumState) GetProbabilities() []float64 {
	probs := make([]float64, len(s.Amplitudes))
	for i, amp := range s.Amplitudes {
		probs[i] = math.Pow(cmplx.Abs(amp), 2)
	}
	return probs
}

// calculatePhase 根据比特串和索引计算相位
func (e *QuantumSequenceEncoder) calculatePhase(index int, bits string) float64 {
	phase := 0.0
	for i, bit := range bits {
		if bit == '1' {
			// 如果该位为1，检查索引的对应位
			if (index>>i)&1 == 1 {
				phase += math.Pi / float64(len(bits))
			}
		}
	}
	return phase
}

// normalize 归一化振幅
func (e *QuantumSequenceEncoder) normalize(amplitudes []complex128) []complex128 {
	var sum float64
	for _, amp := range amplitudes {
		sum += math.Pow(cmplx.Abs(amp), 2)
	}
	
	norm := math.Sqrt(sum)
	if norm > 0 {
		for i := range amplitudes {
			amplitudes[i] /= complex(norm, 0)
		}
	}
	
	return amplitudes
}

// calculateCoherence 计算量子相干性
func (e *QuantumSequenceEncoder) calculateCoherence(amplitudes []complex128) float64 {
	// 使用纠缠熵作为相干性度量
	var coherence float64
	for _, amp := range amplitudes {
		prob := math.Pow(cmplx.Abs(amp), 2)
		if prob > 0 {
			coherence -= prob * math.Log2(prob)
		}
	}
	
	// 归一化到 [0, 1]
	maxEntropy := math.Log2(float64(len(amplitudes)))
	if maxEntropy > 0 {
		coherence /= maxEntropy
	}
	
	return coherence
}

// bytesToBitString 将字节转换为二进制字符串
func (e *QuantumSequenceEncoder) bytesToBitString(data []byte) string {
	bitString := ""
	for _, b := range data {
		bitString += fmt.Sprintf("%08b", b)
	}
	// 限制长度
	if len(bitString) > e.NumQubits {
		bitString = bitString[:e.NumQubits]
	}
	return bitString
}

// bitStringToBytes 将二进制字符串转换为字节
func (e *QuantumSequenceEncoder) bitStringToBytes(bits string) []byte {
	// 填充到8的倍数
	for len(bits)%8 != 0 {
		bits += "0"
	}
	
	bytes := make([]byte, len(bits)/8)
	for i := 0; i < len(bytes); i++ {
		bitChunk := bits[i*8 : (i+1)*8]
		var b byte
		for j, bit := range bitChunk {
			if bit == '1' {
				b |= 1 << uint(7-j)
			}
		}
		bytes[i] = b
	}
	
	return bytes
}
